const {chromium} = require('playwright');

(async () => {
  const browser = await chromium.launch({headless: true});
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://mo.fish/', {waitUntil: 'domcontentloaded', timeout: 10000});

  await page.waitForSelector('#web-article-list > .list-item', {timeout: 10000});
  let eles = await page.$$('#web-article-list > .list-item .list-item-title');
  let cnts = eles.length;

  console.log(cnts);


  for (let i = 0; i < cnts; i++) {
    let newPage;
    try {
      let topic = {};
      let idx = `#web-article-list > .list-item:nth-of-type(${i + 1}) .list-item-title`;
      await page.waitForSelector('#web-article-list > .list-item', {timeout: 10000, state: 'attached'});

      topic.title = await page.$eval(idx, el => el.innerText);
      topic.content = await page.$eval(idx, el => el.href);

      [newPage] = await Promise.all([
        context.waitForEvent('page', {timeout: 10000}),
        page.click(idx),
      ]);

      topic.content = newPage.url();

      console.log(i, cnts, topic);
      newPage.close();
    } catch (e) {
      console.error(e.message);
    } finally {
      if (newPage) {
        newPage.close();
      }
    }
  }

})();
